Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting elements without jQuery

I guess this will be voted down, as it doesn't contain enough jQuery, but here it goes :)

What is the most effective way to get the element(s) returned by the jQuery selector below using plain old javascript?

$('a[title="some title text here"]', top.document)
like image 773
Jørgen Avatar asked Sep 01 '11 06:09

Jørgen


People also ask

How to select specific element in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Is querySelector jQuery?

querySelector() and querySelectorAll() are two jQuery functions which helps the HTML elements to be passed as a parameter by using CSS selectors ('id', 'class') can be selected.

How do you select an element without a class?

In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector. Since it is used to prevent a specific items from list of selected items.

Which is the correct jQuery selector to select the first list item of ul element?

The :first selector selects the first element.


3 Answers

If you're using a modern browser, you could use this:

window.top.document.querySelectorAll('a[title="some title text here"]')
like image 181
icktoofay Avatar answered Oct 02 '22 21:10

icktoofay


Not sure if it’s the most effective, but at least it works.

var links = top.document.getElementsByTagName('a');
var result = [];
var linkcount = links.length;
for ( var i = 0; i < linkcount; i++) {
    if (links[i].getAttribute('title') === 'some title text here') {
        result.push(links[i]);
    }
}
like image 39
margusholland Avatar answered Oct 02 '22 19:10

margusholland


Here is an example

var getElements = function(tagName, attribute, value, callback) {
  var tags = window.document.getElementsByTagName(tagName);
  for (var i=0; i < tags.length; i++) {
    var tag = tags[i];
    if (tag.getAttribute(attribute) == value) {
      callback(tag);
    }
  };
};

getElements("a", "title", "PHP power player at Hettema & Bergsten. Click to learn more.", function(tag) {
  console.log(tag);
});
like image 3
James Kyburz Avatar answered Oct 02 '22 20:10

James Kyburz