How to get a word content from an element and append it to the end of a URL of a href?

Viewed 136

There is a function called "dictionary link" in Anki as the manual explains:

Dictionary Links

You can also use field replacement to create dictionary links.

Imagine you’re studying a language and your favourite online dictionary allows you to search for text using a web URL like: http://example.com/search?q=myword

You could add an automatic link by doing the following in your template:

{{myword}}

<a href="http://example.com/search?q={{myword}}">check in dictionary</a>

The template above would allow you to search for each note’s expression by clicking on the link while reviewing.

I am now learning HTML + CSS + Javascript from scratch, I'd like to add a similar tool in my own practice website. I want to copy the text content (the word that I want to check in the dictionary) of an element, add it to the end of the url. When I click the link the corresponding dictionary page will show up.

For example:

<span id="search">entry</span>

copy "entry" and add it to the end of

<a id="dictionary" href="http://example.com/search?q=">link</a>

Since I am a complete beginner, I haven't learned jQuery or other tools yet. Is it possible to do this only by HTML and Javascript?

4 Answers
const search = document.getElementById("search");
const link = document.getElementById("dictionary");

link.href = `http://example.com/search?q=${search.innerText}`;

You have to assing new href property to link by getting innerText of search element

Did you try to use these apex:

<a href=`http://example.com/search?q=${myword}`>check in dictionary</a>

Otherwise you have to build the link by js script and then assign to a element:

let link = 'http://example.com/search?q=' + customParam
// Fetch the tag <a>
let hrefElement = document.getElementById('#idElement');
// Change the href param with your link
hrefElement.href = link;

Try this link and try to work around

function clicks(){
 var foo = document.getElementById("dictionary").id
 $("a").attr("href", "http://example.com/"+foo+"?q=")
}

document.getElementById("myLink").href = customLink will set your link to your a element

//get input element
var inputElement = document.getElementById('param-input');
// add event to listen every time a letter is introduced
inputElement.addEventListener("keyup", composeUrl);


function composeUrl() {
   // get value from input
   var param = inputElement.value;
   // compose url 
   var customLink = "http://example.com/search?q=" + param
   //set href 
   document.getElementById("myLink").href = customLink
   //get href
   var result = document.getElementById("myLink").href;
   //print link in a div
   document.getElementById("demoLink").innerHTML  = result.toString()
}
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="param-input" />

<a id="myLink" />

<div id="demoLink"> url composed </div>

Related