0

I want to show a message in element in page of wordpress(if parameter "message" in url have a value ).for this purpose i installed "Header and Footer Scripts" plugin.and write this code in "insert script to ":

<script>
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

if(getUrlParameter('message'))
{
const para = document.createElement("p");
const node = document.createTextNode(getUrlParameter('message'));
para.appendChild(node);

const element = document.getElementsByClassName("entry-content");
element.appendChild(para);

}
</script>

but not working. and get error :

?message=ثبت انجام شد:291 Uncaught TypeError: element.appendChild is not a function at ?message=ثبت انجام شد:291

view of page

note:I used embed code plugin instead of "Header and Footer Scripts" plugin.My problem was solved.

3
  • 2
    You seem to be having a few errors, please check your console. Commented Aug 24, 2021 at 6:51
  • ohh yes,i eddited my question. Commented Aug 24, 2021 at 8:09
  • 2
    Yes, that is what i expected. getElementsByClassName returns a collection not a single element. So you need to access its content via element[0].appendChild(para); or whatever index you need Commented Aug 24, 2021 at 8:14

1 Answer 1

1

element = document.getElementsByClassName("entry-content") returns a nodelist of elements and not a single one. therefore calling element.appendChild(para) will not work.

You need to iterate over this nodelist. One possible way would be to use QuerySelectorAll instead of getElementsByClassName :

document.querySelectorAll('.entry-content').forEach(element => {
    element.appendChild(para);

})

Sign up to request clarification or add additional context in comments.

1 Comment

thanks.error has been fixed.but out put is empty: <p>&nbsp;</p>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.