Search through the ID and attribute

3

How to search for div for example through your ID and Attribute in specific like this:

   <div id="Y" data-id="X"></div>

that is, a code that takes a DIV with id=Y and data-id=X

    
asked by anonymous 07.06.2015 / 15:07

2 answers

2

If you want to find an element with both attributes you can use

var div = document.querySelector('#Y[data-id="X"]');
// ou ainda:
var div = document.querySelector('[id="Y"][data-id="X"]');

In this example it becomes redundant to use data-id="X" because #Y must be suffocating since IDs must be unique. But in case of another attribute data- or class you can use like this:

var div = document.querySelector('.minhaClass[data-id="X"]'); 
// ou noutros casos
var div = document.querySelector('[data-custom="Y"][data-id="X"]'); 

That is: CSS selectors must be together, without space, when the idea is to select an element with both attributes.

    
07.06.2015 / 16:02
2

To search for both (Redundant):

$('#Y[data-id="X"]').html('hauahu'); 

To search for id is this way with javascript pure:

var x = document.getElementById("Y");

To search the class (it will return an array with all objects with a given class):

var x = document.getElementsByClassName("example");

Or using jquery:

$("ul").find("[data-id=X]");

This is basically the construction of selectors, which can be used in a variety of functions of jquery .

You can use this construct (supported by all Current browsers) to search for differs.

var x = document.querySelectorAll('[property]');

Sources that say id should be unique:

W3 test

Prgrammers question

W3 Documentation

    
07.06.2015 / 15:24