Search code examples
javascripthtmlreactjsselenium

Capture html content on click


I'm looking for a way to highlight the current html element on mouse-hover (not a specific object, anything the user encounters) and when the user clicks the item I want to copy the content of the current html element.

How can I do that in Javascript? is there a library that I can use?

Thank you


Solution

  • To add a hover effect, just add a :hover rule to your CSS sylings and add the changes in style to it. No need for JS at all. In the below example, the background color changes on hover. Same thing can be done for any element on the page by adding the css rule to the <body> tag instead of a specific object: body *:hover { background-color: steelblue; }

    To add the click event, use JS to add an click listener to either all the items, or to the container of the items. innerHTML will then give you the 'content' of the HTML node that you can do anything with. In the example below, we just send the content to another function that will log it to the console.

    You could write all of this into one statement, but it's usually preferred to break these things down into small pieces so you can mix n match later on when changes are needed.

    var addClick = function( callback ) {
      document.querySelector( '#list_items' ).addEventListener( 'click', function( event ) {
        var item = event.target;
        if ( item.nodeName === 'LI' ) callback( item.innerHTML );
      } );
    };
    var event_handler = function( content ) {
      console.log( 'the content of the clicked item is: ' + content );
    };
    addClick( event_handler );
    .list-item {
      background-color: white;
      border: 1px solid black;
      margin-bottom: 4px;
      padding: 4px;
    }
    .list-item:hover {
      background-color: steelblue;
    }
    <ul id="list_items">
      <li class="list-item">Item 1</li>
      <li class="list-item">Item 2</li>
      <li class="list-item">Item 3</li>
      <li class="list-item">Item 4</li>
    </ul>