Javascript DOM How to - Use document query selector with attribute value








Question

We would like to know how to use document query selector with attribute value.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!-- w  ww .j  av a  2s.  c o  m-->
    var div = document.querySelectorAll('p[foo="bar"]')[0];
    console.log(div.innerHTML)
}
</script>
</head>
<body>
  <p foo="bar">Lorem Ipsum color dot....</p>
</body>
</html>

The code above is rendered as follows: