jQuery(...).html() is undefined

Viewed 39

I'm dealing with a feed that I have no control over. I need to separate the title into two sections, for example:-

<h3>New Clause 12 - Monitoring tool | Order | Committees</h3>

Needs to land as

<h3>New Clause 12 - Monitoring tool</h3><div> Order | Committees </div>

To that end I want to replace the first half pipe with a </h3><div>

jQuery('h3').html(jQuery('h3').html().replace('|', "</h3><div>"));

This works in JS fiddle, but in practice results in jQuery(...).html() is undefined, for the life of me I cannot see why!

http://jsfiddle.net/w6gp2af3/

Edit: This, annoyingly, now that its running in the proper place, seems to replace all the titles on the page with the content of the first title.

1 Answers

If you want to do something like this you need to remember how your code works in a browser. It starts at the top and works it way down. If you have a javascript/jquery script that needs to change some html-elements then you need to make sure that when the browser will try to do this those html-elements already exist/that the can be found.

Probably the easiest solution would be to place your script just before the </body> after all the html-elements. That way you know that everything is all ready loaded and can be adjusted by your script.

If you would want to you can also place the script in the head of the file but then you need to make sure this code is called after everything is loaded. Javascript and jQuery have some functions for this like window.load, or $(document).ready(), and some other eventlisteners

Some code to help with your question:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  <h3>New Clause 12 - Monitoring tool | Order | Committees</h3>
  <h3>New Clause 13 - Different tools | Order | Committees</h3>
  
  <script>
    // Get and prepare the text to split
    let textToSplit = $("h3:first").html().replace(" | ",";");

    // The H3 tag gets to keep the first half
    // After the H3 tag we'll add a div with the second half.
    $("h3:first").html(textToSplit.split(";")[0]);
    $("h3:first").after($("<div>").html(textToSplit.split(";")[1]));

  </script>
</body>
</html>

Related