Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element by tag name and class name

Tags:

javascript

(in vanilla JavaScript) I was wondering if the was an easy way to do something like

x = document.getElementsByTagName('span') && getElementsByClassName('null');

To return all 'span' elements that have the class name 'null'?

I thought it might have been something like:

x = document.getElementsByTagName('span'); 
x = x.getElementsByClassName('null');
// or     
x = document.getElementsByTagName('span').getElementsByClassName('null');

But that didn't seem to work out.

Is this possible or will I have to iterate through x popping anything that returns false for .class='null'?

Thanks.

like image 422
Leke Avatar asked Aug 14 '13 20:08

Leke


People also ask

How do you select an element with the class name?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

Can I use get element by class?

You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s). Warning: This is a live HTMLCollection . Changes in the DOM will reflect in the array as the changes occur.

How do I find element by tag name?

The Java Syntax for locating a web element using its Tag Name is written as: driver. findElement(By. tagName (<htmltagname>))


1 Answers

The DOM does not provide any APIs for filtering NodeLists.

Instead, you can use CSS selectors:

var x = document.querySelectorAll('span.null');
like image 183
SLaks Avatar answered Sep 28 '22 04:09

SLaks