0

I'm trying to replace the .bio__content h4 text with the newLinks content I created in my JS file.

I'm trying to use the forEach function to display the newLinks to the page but it's not working for me. I'm not sure what I'm doing wrong, I want to replace the the .bio__content h4 content with newLinks, so I used the replace() function.

Is this not right?

HTML

 <div class="bio__content">
     <h1 itemprop="name">Name</h1>
        <div>
           <h4><%- profile.designations %></h4>
         </div>
  <div>

JS

var designation = JSContext.profile.designations.split(", ");
// designation = ['CAP', 'AEA', 'AAA']

var newLinks = designation.map(function(x) {
return "<a class='modal'>" + x + "</a>" });
// newLinks = ["<a class='hey'>CAP</a>", "<a class='hey'>AEA</a>", "<a class='hey'>AAA</a>"]

newLinks.forEach(function (e) {
  $(".bio__content").text().replace(".bio__content h4", e);
});

1 Answer 1

1

The replace function is a string function which replaces the a certain value within a string with another value. The function you should use to add html to a document using javascript is $.html(). Also, it would be easier if you joined all links into one html string withe the join function and added it to the document.

var designation = //JSContext.profile.designations.split(", ");
            designation = ['CAP', 'AEA', 'AAA']
            
            var newLinks = designation.map(function(x) {
            return "<a class='modal'>" + x + "</a>" });
            // newLinks = ["<a class='hey'>CAP</a>", "<a class='hey'>AEA</a>", "<a class='hey'>AAA</a>"]
            
             var linksString = newLinks.join("\n");
            $(".bio__content h4").html(linksString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bio__content">
             <h1 itemprop="name">Name</h1>
                <div>
                   <h4><%- profile.designations %></h4>
                 </div>
          <div>

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

Comments

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.