skip to Main Content

I’m having an issue with some ellipsis being automatically added the end of a link with something I am pulling into my site. I really don’t know javascript very well, and am trying to add something in to remove that!

Here’s the code (with a fake link):

<div class="item-title-container">
  <a title="Brewery Packaging Technology Course" href="https://www.link">Brewery Packaging Technology Course...</a>
</div>

Here’s what I’ve tried (3 different options):

let srch = '...';
document.querySelectorAll('.item-title-container').forEach(el => {
  if (el.innerText.indexOf(srch) > -1) el.innerText = el.innerText.split(srch).slice(0, -1).join(srch);
})

let element = document.querySelector('.item-title-container');
element.innerHTML.replace('...','');


var str = document.getElementsByClassName('item-title-container');
str = str.slice(0, -3);

I am obviously not very good at this but looking for a solution!

2

Answers


  1. It’s probably an ellipsis character, not three . characters. You can use a regexp that replaces either.

    element.innerHTML = element.innerHTML.replace(/(...|…)$/, '');
    
    Login or Signup to reply.
  2. Fixing the 2nd Approach

    .innerHTML allows you to access and set the content of a div or some other HTML tags.

    However, you cannot edit the value of .innerHTML, this may sound confusing, here are some examples.

    var x = element.innerHTML; // access the content of element
    
    element.innerHTML = "hello world"; // sets the content of element to "hello world"
    

    You cannot access and set the content with the same .innerHTML, and that’s what you tried by typing element.innerHTML.replace('...','');.

    To fix that try,

    element.innerHTML = element.innerHTML.replace('...','');
    

    Fixing the 3rd Approach

    When .innerHTML is used to access the content, it does not return a reference to the content. That’s the reason why the following code is not working:

    var str = document.getElementsByClassName('item-title-container').innerHTML; // you forgot to add .innerHTML here
    str = str.slice(0, -3);
    

    In the code above, editing str will only edit str. In other words, str is not reference to the element’s innerHTML. In order to make the code work, you have set the innerHTML to str.

    Try the following:

    var str = document.getElementsByClassName('item-title-container').innerHTML;
    str = str.slice(0, -3);
    document.getElementsByClassName('item-title-container').innerHTML = str;
    

    To make the code above easier to read try the following:

    var element = document.getElementsByClassName('item-title-container')
    
    var str = element.innerHTML;
    element.innerHTML = str.slice(0, -3);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search