Skip to content
Advertisement

Remove space or replace with underscore of auto generated ID tags

Completely revising my question.

I am using this code to generate an id tag:

$items.="<h3 id='$heading_old' class='cateory_h' style='width: 100%; display: flow-root; margin: 10px 10px; font-weight: 600; color: #bcd63a;'> $heading_old</a></h3>";

Which produces this html:

<h3 id='Craft Cocktails' class='cateory_h' style='width: 100%; display: flow-root; margin: 10px 10px; font-weight: 600; color: #bcd63a;'> Craft Cocktails</a></h3><div class="beers">

I cant have a space in the id. I need to either remove it on replace it with an underscore.

Is there a way to accomplish this?

This did not work:

document.getElementById("Lighter Beers").id = "Lighter_Beers";

Thanks to Nico Bleiler for pointing out my original code errors!

Advertisement

Answer

For the anchor to work properly the fragment in url has to be identical to the id of the element.

<a href="#test">Go to Test</a>

If you click it it will update the URI fragment and scroll to the element on the page that has the id

<div id="test">Test</div>

Use the method urlencode ( string $str ) : string on your variable like

urlencode($heading_old)

and encode the a tags yourself to match them

I inspected your a tags.

It seems like you used the wrong apostrophe.

The Browser updated your example and corrected it

<a href="“#Craft_Cocktails”">Craft Cocktails</a>

You mixed and "

<ul class="nav2">
    <li><a href="#Craft_Cocktails">Craft Cocktails</a></li>
    <li><a href="#Darker_Beers">Darker Beers</a></li>
    <li><a href="#Lighter_Beers">Lighter Beers</a></li>
    <li><a href="#Hoppy_Beers">Hoppy Beers</a></li>
    <li><a href="#Wild_and_Sour">Wild and Sour</a></li>
    <li><a href="#Wine_and_Cider">Wine and Cider</a></li>
</ul>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement