-3

I am having trouble getting the word number of a word a user has selected

For example

I have a simple paragraph which contains two words Hi and bob

 <p>Hi bob</p>

So logically Hi=1 and bob=2. Now lets assume the user has selected bob I want the Program to log the number 2 to the console now lets assume the user has selected Hi it should log the number 1 to the console. Also this program should work for any amount of words.

Any help would much appreciated

Thanks

fuzzy buddy
  • 99
  • 1
  • 3
  • 10

2 Answers2

1

Basically, you have to pre-process, give each word a number first. Then, make each word become "span" and assign events.

(in my example, i assumed that your "select" means "click" and used jQuery)

  
    var container = $("#text");
    var words = container.text().split(" ");
    var count = 1;
    
    container.html("");
    
    words.forEach(function (word) {
        var span = $("<span></span>");
        span.data("number", count++);
        span.text(word + " ");
        span.click(function () {
            console.log($(this).data("number"))
        });
        container.append(span)
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="text">Hi bob hi bob hi bob</p>
Louis
  • 325
  • 3
  • 11
-1

You can split the words into an array, and use indexOf to get the index:

var text = document.getElementById("text").innerText.split(' ')
var userInput = prompt()
console.log(text.indexOf(userInput) + 1)
<p id="text">Hi bob</p>

I added 1 since you wanted a human-readable version, if i left it without, it would think "hi" is the 0th word.

EDIT: Added prompt.

Kobe
  • 6,226
  • 1
  • 14
  • 35