0

I'm working on a website where I get divs informations (like height) using a method where I get their id depending on the url, with anchors.

I somehow can't manage to make it work with url with space or special characters in them. It works fine with not spaced nor accented letters, but as soon as there are spaces (like in the example) it doesn't work.

I need them to work with spaces & accented characters though.

Here is the code. I think decodeURI() is making things work weirdly...

// My url as I load the page is : https://foo/#Le 10 décembre

// var strurl = window.location.href;
var strurl = "https://foo/#Le%2010%20d%C3%A9cembre";
var idOfText = /#(.+)/.exec(strurl)[1];
// it keeps "Le%2010%20d%C3%A9cembre"
var decodedIdOfText = decodeURI(idOfText)
// it gives me back "Le 10 décembre"

//now that I got this part of the url, 
//I need to find the matching element in my dom, using it's ID :

var x = document.getElementById(decodedIdOfText);
console.log(x)
// this console.log gives me : [object HTMLDivElement] 
// it should give me the specific div#Le 10 décembre

var textHeight = x.height();
// because I'm next supposed to get it's height.
// but there it gives me 
// Uncaught TypeError: x.height is not a function

<div class="text" id="Le 10 décembre">
    <a class="subtitle-texts" id="Le 10 décembre">Le 10 décembre</a>
    <div class="texts">
        <p>Le grand spectacle se termine, la chanson commence à se calmer, devenir plus tendre, le rythme est surement plus lent. Les voix sont reposées, les gestes sont lents</p>    
    </div>
</div>

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
Aurore
  • 696
  • 4
  • 16

1 Answers1

0

Update 1:
Observation 1: You have two elements with same id. The id is supposed to be unique.

<div ... id="Le 10 décembre">
    <a ... id="Le 10 décembre">Le 10 décembre</a>

Observation 2: Is there a good reason to make IDs with spaces, special characters and extended charset containing symbols like é? The IDs are always internal, not part of design, used only to be identified programatically. What is exactly the reason to do things that works against your program?

Look, I don't see a problem with your code. Try it in Mozilla javascript test

encoded="https://foo/#Le%2010%20d%C3%A9cembre";
console.log(decodeURI(encoded));
console.log(decodeURI(/#(.+)/.exec(encoded)[1]));

enter image description here

armagedescu
  • 1,758
  • 2
  • 20
  • 31
  • Hi, thanks for the help. Indeed, this part is working well. That's also why I can't understand why the next part is not working... – Aurore Mar 23 '22 at 21:17
  • @damian Please check Update 1 in the response. By the way, a good idea is to use the debugger and see yourself what exactly is happening in your code. – armagedescu Mar 24 '22 at 10:09