Home > Software engineering >  jQuery selector with a specific ID and a specific attribute value
jQuery selector with a specific ID and a specific attribute value

Time:05-09

Is there a way to select an element that has both a specific ID and a specific attribute value? I'm not finding an option like that in the selector documentation, but I have to imagine it's possible.

For example, an element has ID = foo, and the 'color' attribute set to 'bar'

So far I've got:

$('#myID[myattribute='myvalue']')

CodePudding user response:

here is an example using Template literals. keep in mind "myattribute" is not a valid attribute name. you should prefix if with data-*

let myvalue = 'my-super-value';

$(`#myID[myattribute="${myvalue}"]`).addClass("xxx");

console.log('selector: ', `#myID[myattribute="${myvalue}"]`);
.xxx  {
    color: green;
    border: solid 2px orange;
    width: 100%;
    padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myID" myattribute="my-super-value">my-super-value</div>

CodePudding user response:

For example:

Html:

<p id="data" headers="test">ABC</p>

Jquery:

alert($('#data[headers="test"]').text());
  • Related