javascript

How do you make a button that marks the same word in two div in JS?


illustration of the execution of the button:


Solution

  • You can add mark tag in your Html code with JS. But mark tag works only in HTML5. It will be okay in new Browsers.

    For example this is your html code:

    <div>
        Word1 Word2 Word3 Word1
    </div>
    
    <div>
        Word1
    </div>
    <input type="button" id="button" value="Click" onclick="" />
    

    This is css code:

    div { width:200px;height:200px;border:1px solid black;float:left; }
    

    And this is our javascript code:

    var commonWord = 'Word1';
    var button = document.getElementById('button');
    
    button.addEventListener('click', function () {
        
        var divs = document.getElementsByTagName('div');
        divs[0].innerHTML = divs[0].innerHTML.replace(commonWord, '<mark>' + commonWord + '</mark>');
        divs[1].innerHTML = divs[1].innerHTML.replace(commonWord, '<mark>' + commonWord + '</mark>');
    });
    

    But this JavaScript code marks only first words in divs If you want to mark all words, you can use this:

        var commonWord = 'Word1';
        var button = document.getElementById('button');
    
        button.addEventListener('click', function () {
            
            var divs = document.getElementsByTagName('div');
            divs[0].innerHTML = divs[0].innerHTML.replace(/Word1/g, '<mark>' + commonWord + '</mark>');
            divs[1].innerHTML = divs[1].innerHTML.replace(/Word1/g, '<mark>' + commonWord + '</mark>');
        });