Getting Dom Elements by Classname

How to get element by class name?

The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.

The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:

var y = document.getElementsByClassName('foo');
var aNode = y[0];

If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:

var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);

As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:

  • querySelector(all)
  • getElementsByClassName
  • Don't use w3schools to learn something
  • Refer to MDN for accurate information

react access dom elements by classname in component

The problem that you have got htmlCollection when use document.getElementsByClassName which is not an array
try to do

 const elements = Array.from(document.getElementsByClassName("work"));

and then use

        elements.map(element=>{
element.style.width = eachItemWidth;
})

How to access all dom elements by class name in React?

The onClick on button(both buttons) is continuously calling the function plusDivs, which in turn invokes showDivs. It should be onClick={() => this.plusDivs(-1)}.

How is it possible to get elements by class name in PHP (DOM selectors)?

Use DOMXPath with a custom XPath query. See How can I find an element by CSS class with XPath?

JavaScript get elements by class name and tag name

document.querySelectorAll('ul.active')

Javascript: How to get only one element by class name?

document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array returned.

var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];

Else, if you really want to select only one element. Then you need to use 'id' as conceptually it is used as an identifier for unique elements in a Web Page.

// HTML
<div id="myElement"></div>

// JS
var requiredElement = document.getElementById('myElement');

Getting DOM elements by classname

Update: Xpath version of *[@class~='my-class'] css selector

So after my comment below in response to hakre's comment, I got curious and looked into the code behind Zend_Dom_Query. It looks like the above selector is compiled to the following xpath (untested):

[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]

So the PHP would be:

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

Basically, all we do here is normalize the class attribute so that even a single class is bounded by spaces, and the complete class list is bounded in spaces. Then append the class we are searching for with a space. This way we are effectively looking for and find only instances of my-class .


Use an xpath selector?

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(@class, '$classname')]");

If it is only ever one type of element you can replace the * with the particular tagname.

If you need to do a lot of this with very complex selector I would recommend Zend_Dom_Query which supports CSS selector syntax (a la jQuery):

$finder = new Zend_Dom_Query($html);
$classname = 'my-class';
$nodes = $finder->query("*[class~=\"$classname\"]");

ReactJS, find elements by classname in a React Component

You can use ReactDOM.findDOMNode. Even though the documentation encourage using ref, let's see how it works:

findDOMNode()

ReactDOM.findDOMNode(component)

If this component has been mounted into the DOM, this returns the
corresponding native browser DOM element. This method is useful for
reading values out of the DOM, such as form field values and
performing DOM measurements. In most cases, you can attach a ref to
the DOM node and avoid using findDOMNode at all.

When a component renders to null or false, findDOMNode returns null.
When a component renders to a string, findDOMNode returns a text DOM
node containing that value. As of React 16, a component may return a
fragment with multiple children, in which case findDOMNode will return
the DOM node corresponding to the first non-empty child.


Note: findDOMNode is an escape hatch used to access the underlying DOM
node. In most cases, use of this escape hatch is discouraged because
it pierces the component abstraction. findDOMNode only works on
mounted components (that is, components that have been placed in the
DOM). If you try to call this on a component that has not been mounted
yet (like calling findDOMNode() in render() on a component that has
yet to be created) an exception will be thrown. findDOMNode cannot be
used on functional components.

Also let's look at the ref, which is recommended:

Adding a Ref to a Class Component

When the ref attribute is used on a custom component declared as a
class, the ref callback receives the mounted instance of the component
as its argument. For example, if we wanted to wrap the CustomTextInput
above to simulate it being clicked immediately after mounting:

class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focusTextInput();
}

render() {
return (
<CustomTextInput
ref={(input) => { this.textInput = input; }} />
);
}
}

Note that this only works if CustomTextInput is declared as a class:

class CustomTextInput extends React.Component {
// ...
}

PHP: Getting DOM elements by classname

You can use XPath to easily achieve it.

$page = file_get_contents('http://www.example.com/test');
$doc = new DOMDocument();
$doc->loadHTML($page);

$xpath = new DomXPath($doc);

$nodeList = $xpath->query("//div[@class='inner text-inner']");
$node = $nodeList->item(0);

// To check the result:
echo "<p>" . $node->nodeValue . "</p>";

This will output:

bla bla bla


Related Topics



Leave a reply



Submit