Home > database >  Element.setAttribute only reflects on console
Element.setAttribute only reflects on console

Time:05-27

I'm really new to Web Development. While experimenting with a little JavaScript in HTML, I tried to change the content of an element. When I execute the code below, I get "Updated Content" in the console which is the desired outcome. However, the content inside of the popover does not update.

Why does it only update on the console and not the website?

$(function() {
  $('[data-bs-toggle="popover"]').popover()
  document.getElementById('rex').setAttribute('data-bs-content', 'Updated Content');
  console.log(document.getElementById('rex').getAttribute('data-bs-content'));
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <!-- CSS only -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X R7YkIZDRvuzKMRqM OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
  <!-- JavaScript Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
</head>

<body>
  <a id='rex' href="#" title="Header" data-bs-toggle="popover" data-placement="top" data-bs-content="Content">Click</a>
</body>

</html>

CodePudding user response:

If you want to change the content that appears after the popup is already visible, you need to update the popup itself:

document.getElementsByClassName('popover-body')[0].textContent = 'Updated Content';

CodePudding user response:

I'm still not certain what all you're looking to update, but have a look at this. I didn't change anything in your html. I'm creating an on click binding for the #rex link, and it updates several things... my comments are below. I'm also using only jquery syntax. What you posted is kind of a mix and match of jquery and some pure javascript. You'll help yourself a lot early on paying attention to the difference, but for now since Bootstrap requires jquery its not that big of a deal.

 $(document).on('click', '#rex', function() {
    $(this).text('Updated Content');                          //text of the anchor
    $(this).attr('data-bs-content', 'Updated Content');       //text of the popover
    $(this).popover('show');                                  //trigger popover to show
    // $(this).popover('toggle');                             //or use a toggle
 });

https://jsfiddle.net/otzyd54h/

  • Related