简体   繁体   中英

Change text of span with Javascript - without "OnClick"

I use Squarespace, and have a button on my site that I want the text to change on.

I don't have access to the html, but I can do "javascript::" style stuff with the "button" element. Link to Image

I tried this.innerhtml , but it didn't work.

I've also tried:

<script>
function changeText(boxID)
{
 document.getElementById($(boxID).attr("id")).innerHTML = 'stuff';
}
</script>

and calling javascript::changeText() , but that didn't work.

Its a square space site, so I can't change ID name, and they change every time I change anything on the website. The class names for buttons will select all buttons, so that won't work either.

Update: This on the button in the little link thing: javascript:changeText(this);

This in the code injection panel:

<script>
function changeText(box)
{
    var boxID = box.id;
    alert(box.id);
    console.log('element id = ' + id);
    document.getElementById(boxID).innerHTML = 'stuff';
}
</script>

I get error (index):80 Uncaught TypeError: Cannot set property 'innerHTML' of null

At page load you can do like this.

document.addEventListener("DOMContentLoaded", function(event) {
    document.querySelector('.buttonclassname').innerHTML = 'New text';
    // or an id
    document.querySelector('#buttonid').innerHTML = 'New text';
});

Note, the below ways to find a particular element can of course also be used on page load


Update 2 based on comments

At button click there is a few options.

If the button to target isn't unique in any way (and you have access to html), an inline handler can be attached like this

 function changeText(elem) { elem.innerHTML = 'New text'; }
 <button onclick="changeText(this)">Old text</button> <button>Old text</button> <button>Old text</button> <button>Old text</button> <button>Old text</button>

If you don't have access to the html (and no uniqueness, like an id or class), there might still be uniqueness.

It is always the 3:rd button, do like this

 var btn = document.querySelectorAll("button"); if (btn.length > 2) { btn[2].addEventListener("click", function(e) { e.target.innerHTML = 'New text'; }); }
 <button>Old text</button> <button>Old text</button> <button>Old text</button> <button>Old text</button> <button>Old text</button>

The button contains a know unique text/word

 Array.prototype.slice.call(document.querySelectorAll("button")).forEach(function(btn) { btn.addEventListener("click", function(e) { if (e.target.innerHTML.indexOf('different') > -1) { e.target.innerHTML = 'New text'; } }); });
 <button>Old text</button> <button>Old text</button> <button>Old text</button> <button>Old text is different</button> <button>Old text</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM