w3resource

HTML CSS Exercise: Select elements by attribute

Solution:

HTML Code:

<!doctype html><!-- Declares the document type and version of HTML -->
<html><!-- Opening tag for the HTML document -->
<head><!-- Opening tag for the head section which contains metadata -->
<title>HTML CSS Exercise - Select elements by attribute</title><!-- Title of the HTML document -->
<style> /* Opening tag for CSS styling */
.container[data-name=w3r]{ /* Styles for elements with class 'container' and attribute 'data-name' equal to 'w3r' */
color:#5ac4ed; /* Sets the text color to a shade of blue */
}
</style><!-- Closing tag for CSS styling -->
</head><!-- Closing tag for the head section -->
<body><!-- Opening tag for the body section which contains the content -->
<div class="container" data-name="w3r">Web developemnt tutorials.</div><!-- Container div with attribute 'data-name' set to 'w3r' -->
<div class="container">HTML, CSS, JS, PHP...</div><!-- Container div without the specified attribute -->
</body><!-- Closing tag for the body section -->
</html><!-- Closing tag for the HTML document -->

Explanation:

  • The HTML document consists of two <div> elements with the class 'container'.
  • The first <div> has an additional attribute data-name set to "w3r".
  • CSS styling is applied within <style> tags.
  • The .container[data-name=w3r] selector targets elements with class 'container' and attribute 'data-name' equal to 'w3r'.
  • It sets the text color of these elements to a shade of blue (#5ac4ed).
  • The second <div> does not have the specified attribute, so it does not match the CSS selector and remains unaffected by the styling.

Live Demo:

See the Pen select-elements-by-attribute-answer by w3resource (@w3resource) on CodePen.


Supported browser

Firefox logo Chrome logo Opera logo Safari logo Internet Explorer logo
YesYesYesYesYes

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/html-css-exercise/select-elements-by-attribute-answer.php